﻿Imports ModuloFinanceiro
Imports VendasBLL
Imports VendasDAL
Imports EstoqueBLL
Public Class OrdemServicoFRM
    Dim ObjBLL As New OrdemServicoBLL
    Dim ObjPlaca As New PlacaBLL
    Dim ObjAgendamento As New AgendamentoBLL
    Dim ObjCarro As CarroBLL
    Dim ObjPeca As PECABLL
    Dim ObjServico As ServicoBLL
    Public Codigo, Placodigo As Integer
    Public Op As String
#Region "Métodos"

    Sub CarregaPlaca()
        MTBPlaca.Text = ObjPlaca.Descricao
        TXTCliente.Text = ObjPlaca.CliDescricao
        ObjCarro = New CarroBLL(ObjPlaca.CarCodigo)
        TXTCarro.Text = ObjCarro.Descricao
        TXTModelo.Text = ObjCarro.Modelo
        TXTMarca.Text = ObjCarro.MarcaDescricao
        Placodigo = ObjPlaca.Codigo
    End Sub

    Sub CarregaCampos()
        ObjBLL = New OrdemServicoBLL(Codigo)
        LBCodigo.Text = "Código: " & ObjBLL.OrdCodigo
        ObjPlaca = New PlacaBLL(ObjBLL.CodPlaca)
        CarregaPlaca()
        DGVDados.DataSource = ObjBLL.RetItens(Codigo)
        CBSituacao.SelectedValue = ObjBLL.CodStatus
        TXTNumero.Text = ObjBLL.OrdCodigo
        Placodigo = ObjBLL.CodPlaca
        If (ObjBLL.DataFinal Is Nothing) Then
            MTBDataSaida.Text = ""
            MTBHoraSaida.Text = ""
        Else
            MTBDataSaida.Text = ObjBLL.DataFinal.Value.Date.ToString
            MTBHoraSaida.Text = Format(ObjBLL.DataFinal, "HH") & Format(ObjBLL.DataFinal, "mm")
        End If
        If (ObjBLL.DataInicial Is Nothing) Then
            MTBDataEntrada.Text = ""
            MTBHoraEntrada.Text = ""
        Else
            MTBDataEntrada.Text = ObjBLL.DataInicial.Value.Date
            MTBHoraEntrada.Text = Format(ObjBLL.DataInicial, "HH") & Format(ObjBLL.DataInicial, "mm")
        End If
        ObjPlaca.limpar()
        AtualizaValores()
        PNProdutos.Enabled = True
        PNOperacaoProduto.Enabled = True
        GBPlaca.Enabled = False
        TSBLocalizarAgendamento.Visible = False
    End Sub

    Sub AtualizaValores()

        Dim Total As Decimal = "0.00"
        Dim Desconto As Decimal = "0.00"
        Dim VlMaodeObra As Decimal = "0.00"
        For Each col As DataGridViewRow In DGVDados.Rows
            If col.Cells(7).Value = 10 Then
                VlMaodeObra += col.Cells(6).Value
            Else
                Total += col.Cells(6).Value
            End If

            Desconto += col.Cells(3).Value

        Next
        TXTVlDesconto.Text = Desconto
        TXTVlTotal.Text = (Total + VlMaodeObra) - Desconto
        TXTVlMaoObra.Text = VlMaodeObra
        TXTVlPeca.Text = Total
        TXTVlTotal.Text = FormatCurrency(TXTVlTotal.Text)
        TXTVlDesconto.Text = FormatCurrency(TXTVlDesconto.Text)
        TXTVlPeca.Text = FormatCurrency(TXTVlPeca.Text)
        TXTVlMaoObra.Text = FormatCurrency(TXTVlMaoObra.Text)
    End Sub

    Sub Limpa()
        TXTCarro.Text = ""
        TXTCliente.Text = ""
        TXTMarca.Text = ""
        TXTModelo.Text = ""
        TXTNumero.Text = ""
        TXTVlDesconto.Text = "R$ 0.00"
        TXTVlMaoObra.Text = "R$ 0.00"
        TXTVlPeca.Text = "R$ 0.00"
        TXTVlTotal.Text = "R$ 0.00"
        If DGVDados.DataSource Is Nothing Then
        Else
            Dim Dt As DataTable
            Dt = DGVDados.DataSource
            Dt.Rows.Clear()
            DGVDados.DataSource = Dt
        End If
        LBCodigo.Text = ""
        MTBDataEntrada.Text = Date.Now
        MTBDataSaida.Text = ""
        MTBHoraEntrada.Text = DateTime.Now.ToString("HH:mm")
        MTBHoraSaida.Text = ""
        MTBPlaca.Text = ""
        PNCLiente.Enabled = True
        PNProdutos.Enabled = False
        PNOperacaoProduto.Enabled = False

    End Sub

    Sub ValidaHora()
        Dim Hora As TimeSpan
        Dim Data As DateTime
        ' valida se hora está correta
        If (MTBHoraSaida.Text.Replace(":", "").Replace(" ", "")) <> "" Then

            If (MTBHoraSaida.Text.Replace(":", "").Replace(" ", "")).Count <> 4 Then : Throw New Exception("Hora inválida")
            End If

            If TimeSpan.TryParse(MTBHoraSaida.Text, Hora) = False Then : Throw New Exception("Hora inválida")
            End If

            If (MTBDataEntrada.Text = MTBDataSaida.Text) Then
                If Date.TryParse(MTBDataSaida.Text, Data) Then
                    If (Date.Parse(Hora.ToString) < Date.Parse(MTBHoraEntrada.Text)) Then : Throw New Exception("Horário de saída menor que o de entrada")
                    End If
                End If
            End If

        End If

        If (MTBDataSaida.Text.Replace("/", "").Replace(" ", "")) <> "" Then
            If (MTBHoraSaida.Text.Replace(":", "").Replace(" ", "")) = "" Then
                If MessageBox.Show("Preencher hora?", "Atenção", MessageBoxButtons.YesNo) = vbYes Then
                    MTBHoraSaida.Text = ""
                    MTBHoraSaida.Focus()
                    Throw New Exception("Preencher hora")
                Else
                    MTBDataSaida.Text = ""
                End If
            End If
        End If
    End Sub

    Sub ValidaData()
        Dim Data As DateTime
        Dim Hora As TimeSpan
        'valida se a data está correta
        If (MTBDataSaida.Text.Replace("/", "").Replace(" ", "")) <> "" Then

            If MTBDataSaida.Text.Replace("/", "").Replace(" ", "").Count <> 8 Then : Throw New Exception("Data inválida")
            End If
            'valida se é data
            If Date.TryParse(MTBDataSaida.Text, Data) = False Then : Throw New Exception("Data inválida")
            End If

            'data maior que data de entrada
            If (Data >= FormatDateTime(MTBDataEntrada.Text, DateFormat.ShortDate)) Then
            Else : Throw New Exception("Data de saida menor que o de entrada")
            End If

            If (MTBDataEntrada.Text = MTBDataSaida.Text) Then
                If TimeSpan.TryParse(MTBHoraSaida.Text, Hora) Then
                    If (Date.Parse(MTBHoraSaida.Text) < Date.Parse(MTBHoraEntrada.Text)) Then : Throw New Exception("Horário de saída menor que o de entrada")
                    End If
                End If
            End If
        End If
        If (MTBHoraSaida.Text.Replace(":", "").Replace(" ", "")) <> "" Then
            If (MTBDataSaida.Text.Replace("/", "").Replace(" ", "")) = "" Then
                If MessageBox.Show("Preenchimento da data obrigatorio?", "Atenção", MessageBoxButtons.YesNo) = vbYes Then
                    MTBDataSaida.Text = ""
                    MTBDataSaida.Focus()
                    Finalize()
                Else
                    MTBHoraSaida.Text = ""
                End If
            End If
        End If

    End Sub

    Sub Salva()
        Try
            If (Placodigo > 0) Then
                If (CBMecanico.SelectedValue > 0) Then
                    Dim DataFinal As Nullable(Of DateTime)
                    Dim DataInicial As Nullable(Of DateTime)
                    Dim Data As DateTime
                    Dim Total As Nullable(Of Decimal)
                    Dim Desconto As Nullable(Of Decimal)
                    Dim Res As Decimal
                    If DateTime.TryParse(MTBDataSaida.Text & " " & MTBHoraSaida.Text, Data) And (MTBHoraSaida.Text.Replace(":", "").Replace(" ", "")) <> "" And ((MTBDataSaida.Text.Replace("/", "").Replace(" ", "")) <> "") Then : DataFinal = Data
                    Else : DataFinal = Nothing
                    End If
                    If DateTime.TryParse(MTBDataEntrada.Text & " " & MTBHoraEntrada.Text, Data) Then : DataInicial = Data
                    Else : DataInicial = Nothing
                    End If
                    If Decimal.TryParse(TXTVlTotal.Text.Replace("R$", "").Replace(" ", ""), Res) Then : Total = Res
                    Else : Total = Nothing
                    End If
                    If Decimal.TryParse(TXTVlDesconto.Text.Replace("R$", "").Replace(" ", ""), Res) Then : Desconto = Res
                    Else : Desconto = Nothing
                    End If
                    ObjBLL = New OrdemServicoBLL(Codigo, Placodigo, CBSituacao.SelectedValue, CBMecanico.SelectedValue, DataInicial, DataFinal, Total, Desconto)
                    If (Op = "I") Then
                        Codigo = ObjBLL.IAEOrdem("I")
                        Op = "A"
                    Else
                        ObjBLL.IAEOrdem("A")

                    End If
                    TXTNumero.Text = Codigo
                Else : Throw New Exception("Selecione um mecânico/atendente")
                End If
            Else : Throw New Exception("Informe placa")
            End If
        Catch ex As Exception
            Throw
        End Try
    End Sub

#End Region

#Region "Eventos"

#Region "Pintar datagridview"
    Private Sub DGVDados_RowPrePaint(sender As System.Object, e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DGVDados.RowPrePaint
        If DGVDados.Rows(e.RowIndex).Index Mod (2) = 1 Then
            DGVDados.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Gainsboro
        End If
    End Sub
#End Region

#Region "Placa"
    Private Sub MTBPlaca_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MTBPlaca.KeyPress
        If e.KeyChar = Convert.ToChar(Keys.Return) Then
            Dim ObjP As New ConsultaPlacasFRM
            ObjP.Tipo = "ret"
            ObjP.CBFiltro.SelectedIndex = 1
            ObjP.TXTLocalizar.Text = Trim(MTBPlaca.Text).Replace(" ", "")
            ObjP.ShowDialog()
            If (Not IsNothing(ObjP.ObjP)) Then
                ObjPlaca = ObjP.ObjP
                CarregaPlaca()
                Salva()
                PNProdutos.Enabled = True
                PNOperacaoProduto.Enabled = True
                GBPlaca.Enabled = False
                TSBLocalizarAgendamento.Visible = False
            Else
                Placodigo = 0
            End If
            ObjP = Nothing
        End If
    End Sub

    Private Sub MTBPlaca_Leave(sender As System.Object, e As System.EventArgs) Handles MTBPlaca.Leave

        If (MTBPlaca.Text.Replace("-", "").Replace(" ", "").Count <> 7) Then
            TXTCarro.Text = ""
            MTBPlaca.Text = ""
            TXTCliente.Text = ""
            TXTModelo.Text = ""
            TXTMarca.Text = ""
            Placodigo = 0
            PNProdutos.Enabled = False
        Else
            PNProdutos.Enabled = True
        End If
    End Sub



#End Region

    Private Sub MTBDataSaida_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MTBDataSaida.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            SendKeys.Send("{TAB}")
        End If

    End Sub

    Private Sub MTBHoraSaida_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MTBHoraSaida.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            SendKeys.Send("{TAB}")
        End If
    End Sub

#Region "Data Saida"
    Private Sub MTBDataSaida_Leave(sender As System.Object, e As System.EventArgs) Handles MTBDataSaida.Leave
        Try
            ValidaData()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            MTBDataSaida.Text = ""
            MTBDataSaida.Focus()
        End Try
    End Sub
#End Region

#Region "Hora saida"
    Private Sub MTBHoraSaida_Leave(sender As System.Object, e As System.EventArgs) Handles MTBHoraSaida.Leave
        Try
            ValidaHora()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            MTBHoraSaida.Text = ""
            MTBHoraSaida.Focus()
        End Try
    End Sub
#End Region

#Region "DatagridView alterar"
    Private Sub DGVDados_CellDoubleClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVDados.CellDoubleClick
        TSBALterar_Click(Nothing, Nothing)
    End Sub
#End Region

#Region "DatagridView deletar"
    Private Sub DGVDados_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles DGVDados.KeyDown
        If (e.KeyCode = Keys.Delete) Then
            TSBExcluir_Click(Nothing, Nothing)
        End If
    End Sub
#End Region

#Region "DatagridView alterar"
    Private Sub DGVDados_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles DGVDados.KeyPress
        If e.KeyChar = Convert.ToChar(Keys.Return) Then
            TSBALterar_Click(Nothing, Nothing)
        End If
    End Sub
#End Region

#Region "Fechar formulário com esc"

    Private Sub OrdemServicoFRM_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region


#End Region

#Region "Load"
    Private Sub OrdemServicoFRM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        objconexao.carregaCombo(CBMecanico, "Vendas.Ofi_Funcionario", "fun_codigo", "fun_nome", "sta_codigo < 3", "fun_nome")
        objconexao.carregaCombo(CBSituacao, "Generico.Gen_Status", "sta_codigo", "sta_descricao", "sta_codigo >11 and sta_codigo < 20", "sta_descricao")
        CBMecanico.SelectedIndex = 0
        CBSituacao.SelectedIndex = 0
        GBPlaca.Enabled = True
        Limpa()
        If (Op = "I") Then
            TSBLocalizarAgendamento.Visible = True
            Codigo = 0
            Placodigo = 0
        Else
            CarregaCampos()
        End If
    End Sub
#End Region

#Region "Botões"

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Localizar placa"
    Private Sub BTNLocalizar_Click(sender As System.Object, e As System.EventArgs) Handles BTNLocalizar.Click
        Try
            Dim ObjP As New ConsultaPlacasFRM
            ObjP.Tipo = "ret"
            ObjP.ShowDialog()
            If (Not IsNothing(ObjP.ObjP)) Then
                ObjPlaca = ObjP.ObjP
                CarregaPlaca()
                Salva()
                PNProdutos.Enabled = True
                PNOperacaoProduto.Enabled = True
                GBPlaca.Enabled = False
                TSBLocalizarAgendamento.Visible = False
            End If
            ObjP = Nothing
            ObjCarro.limpar()
            ObjPlaca.limpar()
        Catch ex As Exception
            Throw
        End Try

    End Sub
#End Region

#Region "Salvar"
    Private Sub TSBSalvar_Click(sender As System.Object, e As System.EventArgs) Handles TSBSalvar.Click
        Try
            Salva()
            MessageBox.Show("Ordem de serviço gravado com sucesso!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

#End Region

#Region "Localizar Agendamento"
    Private Sub TSBLocalizar_Click(sender As System.Object, e As System.EventArgs) Handles TSBLocalizarAgendamento.Click
        Try
            Dim ObjA As New ConsultaAgendamentosFRM
            ObjA.Tipo = "ret"
            ObjA.ShowDialog()
            If (Not IsNothing(ObjA.ObjA)) Then
                ObjAgendamento = ObjA.ObjA
                Op = "A"
                Codigo = ObjBLL.InsereAgendamento(ObjAgendamento.Codigo)
                CarregaCampos()
            End If
        Catch ex As Exception
            Throw
        End Try

    End Sub
#End Region

#Region "Incluir"
    Private Sub TSBIncluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBIncluir.Click
        Try
            Dim Objordem As New OrdemProdutosFRM
            Objordem.CodOrdem = Codigo
            Objordem.ShowDialog()
            DGVDados.DataSource = ObjBLL.RetItens(Codigo)
            AtualizaValores()
            While Objordem.Insere = "+"
                Objordem.ShowDialog()
                DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                AtualizaValores()
                Salva()
            End While
        Catch ex As Exception
            Throw
        End Try
    End Sub
#End Region

#Region "Alterar"
    Private Sub TSBALterar_Click(sender As System.Object, e As System.EventArgs) Handles TSBALterar.Click
        Try
            Dim cod As Integer = 0
            Dim indice As Integer = -1
            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                OrdemProdutosFRM.Op = "A"
                OrdemProdutosFRM.CodOrdem = (DGVDados.Rows(indice).Cells("ord_codigo").Value)
                OrdemProdutosFRM.ProCodigo = (DGVDados.Rows(indice).Cells("pro_codigo").Value)
                OrdemProdutosFRM.ShowDialog()
                DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                AtualizaValores()
                Salva()
            Else : Throw New Exception("Selecione o produto/serviço a ser excluido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally

        End Try
    End Sub
#End Region

#Region "Excluir"
    Private Sub TSBExcluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBExcluir.Click
        Try
            Dim cod As Integer = 0
            Dim indice As Integer = -1
            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("sta_descricao") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                If MessageBox.Show("Confirma exclusão do produto/serviço: " & DGVDados.Rows(indice).Cells("pro_descricao").Value.ToString() & " ?", "", MessageBoxButtons.YesNo) = vbYes Then
                    Salva()
                    ObjBLL = New OrdemServicoBLL(Codigo, DGVDados.Rows(indice).Cells("pro_codigo").Value)
                    ObjBLL.IAEItens("E")
                    DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                    AtualizaValores()
                End If
            Else : Throw New Exception("Selecione o produto/serviço a ser excluido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally
        End Try
    End Sub
#End Region
#End Region



End Class